<?php
/*
  Microblog bot for game release notifications
  Copyright (C) 2017  Alexander Yakovlev

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

use League\HTMLToMarkdown\HtmlConverter;
use Mremi\UrlShortener\Model\Link;
class Game {
  public $url;
  public $title;
  public $author;
  public $description;
  public $date;
  public function text() {
    global $bitlyProvider;
    $link = new Link;
    try {
      $link->setLongUrl($this->url);
      $bitlyProvider->shorten($link);
      $link = $link->getShortUrl();
    } catch (Exception $e) {
      echo $e->getMessage()."\n";
      $link = '';
    }

    $title = $this->author.' “'.$this->title.'”';
    $description = $this->description;
    $image = NULL;
    $description = $this->formatdsc($description);
    $limit = 500 - strlen($link) - strlen($title) - 5;
    $description = "$title\n\n".$this->ellipse($description, $limit);
    $description .= "\n$link";
    return $description;
  }
  protected function formatdsc($description) {
    global $pandoc;
    $description = strip_tags($description, 'img');
    $description = $pandoc->runWith($description, [
      'from' => 'html',
      'to' => 'plain',
      'wrap' => 'none'
    ]);
    $description = str_replace('Читать дальше', '', $description);
    $description = trim($description);
    return $description;
  }
  protected function ellipse($str,$n_chars,$crop_str='[...]')
  {
    $buff = $str;
    if(strlen($buff) > $n_chars)
    {
      $cut_index=strpos($buff,' ',$n_chars);
      $buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
    }
    return $buff;
  }

}
